package com.jsz.peini.controller.app;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.jsz.peini.bean.square.SquareComment;
import com.jsz.peini.bean.square.SquareImage;
import com.jsz.peini.bean.square.SquareInfo;
import com.jsz.peini.bean.square.SquareLike;
import com.jsz.peini.bean.user.UserInfo;
import com.jsz.peini.common.constants.Constants;
import com.jsz.peini.common.util.FileUtils;
import com.jsz.peini.common.util.PeiniUtils;
import com.jsz.peini.common.util.ShieldTextFiltration;
import com.jsz.peini.mapper.comm.ImageFilterResultMapper;
import com.jsz.peini.mapper.square.SquareImageMapper;
import com.jsz.peini.mapper.user.UserInfoMapper;
import com.jsz.peini.redis.base.RedisConstants;
import com.jsz.peini.redis.base.RedisUtil;
import com.jsz.peini.redis.base.SerializeUtil;
import com.jsz.peini.server.thread.UserSquareThread;
import com.jsz.peini.service.square.SquareCommentService;
import com.jsz.peini.service.square.SquareInfoService;
import com.jsz.peini.service.square.SquareLikeService;
import com.jsz.peini.service.user.UserInfoService;
import com.jsz.peini.vo.ImgVo;
import com.jsz.peini.vo.UserConcerVo;

@Controller
public class SquareInfoController {
	private static final Logger logger = LoggerFactory.getLogger(SquareInfoController.class);
	@Autowired
	private SquareInfoService squareInfoService;

	@Autowired
	private SquareLikeService squareLikeService;

	@Autowired
	private SquareCommentService squareCommentService;

	@Autowired
	private UserInfoService userInfoService;
	@Resource
	private ImageFilterResultMapper imageFilterResultMapper;
	@Resource
	private SquareImageMapper squareImageMapper;
	@Resource
	private UserInfoMapper userInfoMapper;

	/**
	 * 增加和取消点赞
	 * 
	 * @param request
	 * @param squareId
	 *            广场id,userId 点赞人的id
	 * @return
	 */
	@RequestMapping(value = "/goSquareLike")
	@ResponseBody
	public Object addLove(HttpServletRequest request, Integer squareId, String userId) {
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		infoMap.put("resultCode", Constants.SUCCESS);
		infoMap.put("resultDesc", "成功");
		try {
			String reqUser = userId;
			SquareLike squareLike = new SquareLike();
			squareLike.setSquareInfoId(squareId);
			
			JSONObject obj = PeiniUtils.validToken(userId);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			userId = obj.getString("userId");
			
			squareLike.setUserId(userId);
			List<SquareLike> list = squareLikeService.selectByUser(squareLike);
			int result = 0;
			// 点过赞了则取消点赞
			if (list.size() > 0) {
				result = squareLikeService.delete(squareLike);
			} else {// 没点过赞则点赞
				result = squareLikeService.insert(squareLike);
			}
			if (result > 0) {
				List<HashMap<String, Object>> likeList = squareLikeService.selectBySquareId(squareId);
				for (HashMap<String, Object> hashMap : likeList) {
					if(hashMap.get("userId").toString().equals(userId)){
						hashMap.put("userId", reqUser);
					}
				}
				infoMap.put("likeList", likeList);
				infoMap.put("likeCount", likeList.size());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			infoMap.put("resultCode", Constants.FAIL);
			infoMap.put("resultDesc", "网络请求失败");
		}
		return infoMap;
	}

	/**
	 * 上传广场消息
	 * 
	 * @param request
	 * @param file
	 * @param reportInfoId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/setSquareInfoBySquareInfo", method = RequestMethod.POST)
	@ResponseBody
	public Object setSquareInfoBySquareInfo(HttpServletRequest request,
			@RequestParam(value="userId") String userToken,
			@RequestParam(value="xpoint") String xpoint,
			@RequestParam(value="ypoint") String ypoint,
			@RequestParam(value="content") String content,
			@RequestParam(value="address") String address,
			@RequestParam("file") CommonsMultipartFile[] file) {
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		infoMap.put("resultCode", Constants.SUCCESS);
		infoMap.put("resultDesc", "成功");
		// 判断文件是否为空
		try {
			String newcontent=ShieldTextFiltration.filter(content);
				if (!content.equals(newcontent)) {
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "您发布的信息涉及敏感字词请重新发送!");
					return infoMap;
				}
			JSONObject obj = PeiniUtils.validToken(userToken);
			if(obj.getInteger("resultCode") != 1){
				return obj.toString();
			}
			String userId = obj.getString("userId");
			//UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
			
			SquareInfo squareInfo = new SquareInfo();
			squareInfo.setUserId(userId);
			squareInfo.setAddress(address);
			squareInfo.setContent(content);
			squareInfo.setXpoint(xpoint);
			squareInfo.setYpoint(ypoint);
			
			int squareInfoNum = squareInfoService.setSquareInfoBySquareInfo(squareInfo);
			if (squareInfoNum > 0 && file != null) {
				
				// 返回添加信息id
				SquareInfo squareInfo2 = squareInfoService.selectSquareInfoIdByUserId(squareInfo.getUserId());
				String filePath = "/upload/square/";
				for (MultipartFile fileMap : file) {
					// 判断文件是否为空
					if (!fileMap.isEmpty()) {
						String resultPath = FileUtils.uploadSquareFile(request,fileMap, filePath);
						
						SquareImage squareImage = new SquareImage();
						squareImage.setImageSrc(resultPath);
						
						squareImage.setImageSmall(resultPath+"?imageView2/1/w/350");
						
						squareImage.setSquareInfoId(squareInfo2.getId());
						squareImage.setImageTime(new Date());
						squareImageMapper.insert(squareImage);
						
						ImgVo imgVo = new ImgVo();
						imgVo.setImgUrl(resultPath);
						imgVo.setParamId(squareImage.getId().toString());
						imgVo.setType(1);
						RedisUtil.lpush(RedisConstants.IMG_CHECK.getBytes(), SerializeUtil.serialize(imgVo));
					}
				}
			}
			/*UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(userId);
			UserConcerVo concerVo = new UserConcerVo(newuserInfo.getId(), null, null,1, newuserInfo.getNickname(), newuserInfo.getAccCode(), newuserInfo.getSignWord());
			UserSquareThread.userInfo.add(concerVo);*/
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
		}
		return infoMap;
	}

	/**
	 * 上传广场消息
	 * 
	 * @param request
	 * @param file
	 * @param reportInfoId
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/setSquareInfoBySquareInfoNull", method = RequestMethod.POST)
	@ResponseBody
	public Object setSquareInfoBySquareInfoNull(HttpServletRequest request,
			@RequestParam(value="userId") String userToken,
			@RequestParam(value="xpoint") String xpoint,
			@RequestParam(value="ypoint") String ypoint,
			@RequestParam(value="content") String content,
			@RequestParam(value="address") String address) {
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		// 判断文件是否为空
		try {
			String newcontent=ShieldTextFiltration.filter(content);
			if (!newcontent.equals(content)) {
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "您发布的信息涉及敏感字词请重新发送!");
				return infoMap;
			}
			if(StringUtils.isBlank(userToken)){
				infoMap.put("resultCode", Constants.EXCEPTION);
				infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
				return infoMap;
			}
			
			JSONObject obj = PeiniUtils.validToken(userToken);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			String userId = obj.getString("userId");
			
			SquareInfo squareInfo = new SquareInfo();
			squareInfo.setUserId(userId);
			squareInfo.setAddress(address);
			squareInfo.setContent(content);
			squareInfo.setXpoint(xpoint);
			squareInfo.setYpoint(ypoint);
			
			int squareInfoNum = squareInfoService.setSquareInfoBySquareInfo(squareInfo);
			if (squareInfoNum > 0) {
				
				/*SquareVo squareVo = new SquareVo();
				squareVo.setId(squareInfo.getId().toString());
				squareVo.setAddress(address);
				squareVo.setContent(content);
				squareVo.setImageHead(StringUtils.trimToEmpty(userInfo.getImageHead()));
				squareVo.setNickName(StringUtils.trimToEmpty(PeiniUtils.updateNickName(userInfo.getNickname(),userInfo.getAccCode())));
				squareVo.setSquareTime(DateTimeUtils.formatDateTime2String(new Date(), "yyyy-MM-dd HH:mm"));
				squareVo.setUserId(userId);
				SquareRedisUtil.addInfoToRedis(squareVo);*/
				
				infoMap.put("resultCode", Constants.SUCCESS);
				infoMap.put("resultDesc", "成功");
				UserInfo newuserInfo = userInfoMapper.selectByPrimaryKey(userId);
				UserConcerVo concerVo = new UserConcerVo(newuserInfo.getId(), null, null,1, newuserInfo.getNickname(), newuserInfo.getAccCode(), newuserInfo.getSignWord());
				UserSquareThread.userInfo.add(concerVo);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
		}
		return infoMap;
	}

	/**
	 * 增加广场评论
	 * 
	 * @param request
	 * @param squareInfoId
	 *            广场id,userId 评论者id,toUserId 被回复者id,content 评论内容,
	 * @return
	 */
	@RequestMapping(value = "/goComment")
	@ResponseBody
	public Object goComment(HttpServletRequest request, SquareComment squareComment) {
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		infoMap.put("resultCode", Constants.SUCCESS);
		infoMap.put("resultDesc", "成功");
		try {
			String anobject=ShieldTextFiltration.filter(squareComment.getContent());
			if (!squareComment.getContent().equals(anobject)) {
				infoMap.put("resultCode", Constants.FAIL);
				infoMap.put("resultDesc", "您发布的信息涉及敏感字词请重新发送!");
				return infoMap;
			}
			String reqUser = squareComment.getUserId();
			JSONObject obj = PeiniUtils.validToken(squareComment.getUserId());
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			String userId = obj.getString("userId");
			squareComment.setUserId(userId);
			
			UserInfo myUser = userInfoService.selectByUserId(squareComment.getUserId());
			if (StringUtils.isNotBlank(PeiniUtils.updateNickName(myUser.getNickname(),myUser.getAccCode()))) {
				squareComment.setUserNickname(myUser.getNickname());
			} else {
				squareComment.setUserNickname("");
			}

			if (!squareComment.getToUserId().equals("0")) {
				UserInfo toUser = userInfoService.selectByUserId(squareComment.getToUserId());
				if (StringUtils.isNotBlank(toUser.getNickname())) {
					squareComment.setToUserNickname(PeiniUtils.updateNickName(toUser.getNickname(),toUser.getAccCode()));
				} else {
					squareComment.setToUserNickname("");
				}
			} else {
				squareComment.setToUserNickname("");
			}

			int result = squareCommentService.insert(squareComment);
			if (result > 0) {
				List<LinkedHashMap<String, Object>> commentList = squareCommentService.selectBySquareId(squareComment.getSquareInfoId());
				for (LinkedHashMap<String, Object> linkedHashMap : commentList) {
					String mapUser = linkedHashMap.get("userId").toString();
					if (linkedHashMap.get("accCode")!=null&&linkedHashMap.get("userNickname")!=null) {
						linkedHashMap.put("userNickname",PeiniUtils.updateNickName(linkedHashMap.get("userNickname").toString(), linkedHashMap.get("accCode").toString()));
					}
					if (linkedHashMap.get("toaccCode")!=null&&linkedHashMap.get("toUserNickname")!=null) {
						linkedHashMap.put("toUserNickname",PeiniUtils.updateNickName(linkedHashMap.get("toUserNickname").toString(), linkedHashMap.get("toaccCode").toString()));
					}
					if(userId.equals(mapUser)){
						linkedHashMap.put("userId", reqUser);
					}
				}
				infoMap.put("commentList", commentList);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			infoMap.put("resultCode", Constants.FAIL);
			infoMap.put("resultDesc", "网络请求失败");
		}
		return infoMap;
	}

	/**
	 * 删除广场评论
	 * 
	 * @param request
	 * @param id
	 * 单条评论唯一id
	 * @return
	 */
	@RequestMapping(value = "/delComment")
	@ResponseBody
	public Object delComment(HttpServletRequest request,
			@RequestParam(value="id") Integer id,
			@RequestParam(value="userToken") String userToken) {
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		infoMap.put("resultCode", Constants.SUCCESS);
		infoMap.put("resultDesc", "成功");
		try {
			JSONObject obj = PeiniUtils.validToken(userToken);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			String userId = obj.getString("userId");
			
			SquareComment comm = squareCommentService.selectByPrimaryKey(id);
			if(!comm.getUserId().equals(userId)){
				infoMap.put("resultCode", Constants.EXCEPTION);
				infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
				return infoMap;
			}
			
			int result = squareCommentService.delete(id);
			// if(result>0){
			// List<LinkedHashMap<String,Object>> commentList =
			// squareCommentService.selectBySquareId(squareInfoId);
			// infoMap.put("commentList", commentList);
			// }
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
		}
		return infoMap;
	}

	/**
	 * 广场信息删除（所有信息包含照片和描述信息）
	 * 
	 * @param request
	 * @param imageId
	 * @return
	 */
	@RequestMapping(value = "/deleteSquareAll")
	@ResponseBody
	public Object deleteSquareAll(HttpServletRequest request,
			@RequestParam(value="squareInfoId") Integer squareInfoId,
			@RequestParam(value="userToken") String userToken) {
		HashMap<String, Object> infoMap = new HashMap<String, Object>();
		try {
			
			JSONObject obj = PeiniUtils.validToken(userToken);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			String userId = obj.getString("userId");
			
			SquareInfo info = squareInfoService.selectByPrimaryKey(squareInfoId);
			if(!info.getUserId().equals(userId)){
				infoMap.put("resultCode", Constants.EXCEPTION);
				infoMap.put("resultDesc", Constants.EXCEPTION_DESC);
				return infoMap;
			}
			squareInfoService.deleteSquareAll(squareInfoId);
			infoMap.put("resultCode", Constants.SUCCESS);
			infoMap.put("resultDesc", "删除成功");
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
		}
		return infoMap;
	}

	/**
	 * 广场详细信息查询
	 * 
	 * @param request
	 * @param userId
	 *            用户id,pageNow 页码,pageSize 每页条数
	 * @return
	 */
	@RequestMapping(value = "/getSquareInfoList")
	@ResponseBody
	public Object getSquareInfoList(HttpServletRequest request,
			@RequestParam(value="userId") String reqUser,
			@RequestParam(value="otherId",required=false) String otherId,
			@RequestParam(value="type",required=false,defaultValue="0") Integer type,//1我的广场；2他人的广场，0所有广场信息
			Integer pageNow, Integer pageSize) {
		LinkedHashMap<String, Object> infoMap = new LinkedHashMap<String, Object>();
		infoMap.put("resultCode", Constants.SUCCESS);
		infoMap.put("resultDesc", "成功");
		try {
			
			String userId = "";
			String reqUserId = "";
			
			JSONObject obj = PeiniUtils.validToken(reqUser);
			if(obj.getInteger("resultCode") != 1){
				return obj;
			}
			reqUserId = obj.getString("userId");
			
			List<LinkedHashMap<String, Object>> squareList = new ArrayList<LinkedHashMap<String,Object>>();
			Page<?> page = PageHelper.startPage(pageNow, pageSize);
			if(type == 0){
				squareList = squareInfoService.selectSquareListByUserId(null);
				userId = null;
			}else if(type == 1){
				userId = reqUserId;
				squareList = squareInfoService.selectSquareListByUserId(userId);
			}else if(type == 2){
				if(StringUtils.isBlank(otherId)){
					infoMap.put("resultCode", Constants.FAIL);
					infoMap.put("resultDesc", "参数为空");
				}
				userId = otherId;
				squareList = squareInfoService.selectSquareListByUserId(userId);
			}
			
			//Page<?> page = PageHelper.startPage(pageNow, pageSize);
			//List<LinkedHashMap<String, Object>> squareList = squareInfoService.selectSquareListByUserId(userId);
			for (LinkedHashMap<String, Object> squareMap : squareList) {
				UserInfo userBean = userInfoService.selectByUserId((String) squareMap.get("userId"));
				if(userBean == null ){
					continue;
				}
				
				if(reqUserId.equals((String) squareMap.get("userId"))){
					squareMap.put("userId", reqUser);
				}
				
				squareMap.put("nickname", StringUtils.trimToEmpty(PeiniUtils.updateNickName(userBean.getNickname(),userBean.getAccCode())));
				squareMap.put("imageHead", StringUtils.trimToEmpty(userBean.getImageHead()));

				// 获取图片列表
				List<LinkedHashMap<String, Object>> imageList = squareInfoService
						.selectsquareImageBySquareInfoId((int) squareMap.get("id"));
				for (LinkedHashMap<String, Object> imgMap : imageList) {
					if(StringUtils.isBlank(imgMap.get("imageSmall").toString())){
						imgMap.put("imageSmall", imgMap.get("imageSrc").toString());
					}
					
					/*try {  
					     URL url = new URL("http://okxm4c2gg.bkt.clouddn.com/"+imgMap.get("imageSmall"));  
					     InputStream in = url.openStream();  
					} catch (Exception e1) {  
					     logger.info("连接打不开!");  
					     imgMap.put("imageSmall", imgMap.get("imageSrc").toString());
					} */
				}
				squareMap.put("imageList", imageList);

				// 获取点赞人
				boolean isLike = false;
				List<HashMap<String, Object>> likeList = squareLikeService.selectBySquareId((int) squareMap.get("id"));
				for (HashMap<String, Object> hashMap : likeList) {
					if(reqUserId.equals((String) hashMap.get("userId"))){
						isLike = true;
						hashMap.put("userId", reqUser);
					}
					if (hashMap.get("userNickname")!=null&&hashMap.get("accCode")!=null) {
						hashMap.put("userNickname",PeiniUtils.updateNickName(hashMap.get("userNickname").toString(), hashMap.get("accCode").toString()));
					}
					if(StringUtils.isBlank(hashMap.get("imageHead").toString())){
						hashMap.put("imageHead", "/upload/headImg/18202230518.png2017/4/4/ed1fd24bc48a4a46b2e418c4735ad946.png");
					}
				}
				squareMap.put("isLike", isLike);
				squareMap.put("likeList", likeList);

				// 获取评论
				List<LinkedHashMap<String, Object>> commentList = squareCommentService
						.selectBySquareId((int) squareMap.get("id"));
				for (LinkedHashMap<String, Object> linkedHashMap : commentList) {
					if (linkedHashMap.get("accCode")!=null) {
						linkedHashMap.put("userNickname", PeiniUtils.updateNickName(linkedHashMap.get("userNickname").toString(),linkedHashMap.get("accCode").toString()));
					}
					if (linkedHashMap.get("toaccCode")!=null) {
						linkedHashMap.put("toUserNickname", PeiniUtils.updateNickName(linkedHashMap.get("toUserNickname").toString(),linkedHashMap.get("toaccCode").toString()));
					}
					if(reqUserId.equals(linkedHashMap.get("userId").toString())){
						linkedHashMap.put("userId", reqUser);
					}
					if(reqUserId.equals(linkedHashMap.get("toUserId").toString())){
						linkedHashMap.put("toUserId", reqUser);
					}
				}
				squareMap.put("commentList", commentList);
			}
			infoMap.put("squareList", squareList);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			infoMap.put("resultCode", Constants.EXCEPTION);
			infoMap.put("resultDesc", "网络请求失败");
		}
		//logger.info(net.sf.json.JSONObject.fromObject(infoMap));
		return infoMap;
	}

}
